#!/bin/bash

# 加载必要的库
function git_lib() {
    git clone http://10.0.0.66/autodev/kylinsecos/os_libs/lib.git &>/dev/null
    source "./lib/utils.sh"
}

# 前提是不能修改gitlab仓库，否则提交不同
function log_gitlab() {
    local gitlab_log_source="$1"
    local tool_name=$(basename ${gitlab_log_source} .git)
    # 获取 GitLab 仓库的最新提交 ID
    local gitlab_commit=$(git ls-remote "${gitlab_log_source}" HEAD | awk '{print $1}')

    # 比较提交 ID，确认是否上传了最新的代码
    if [ "${github_commit}" == "${gitlab_commit}" ]; then
        log_title "${tool_name}最新的代码已经成功上传到 GitLab！"
    else
        log_title "【原则上不能修改gitlab源代码】GitHub 和 GitLab 的提交记录不同，推送未成功。"
        log_title "GitHub 最新提交: ${github_commit}"
        log_title "GitLab 最新提交: ${gitlab_commit}"
        exit 1
    fi
}

# 单个仓库的克隆和推送操作
function clone_push_single() {
    local target_clone="$1"     # GitHub 仓库地址
    local opensource_clone="$2" # GitLab 仓库地址
    local tool_name=$(basename ${target_clone} .git)

    # 如果仓库目录存在，先删除
    if [ -d "${tool_name}" ]; then
        rm -rf "${tool_name}"
        title_assert "rm -rf ${tool_name}"
    fi

    # 克隆 GitHub 仓库
    git clone "${target_clone}" || {
        echo "GitHub 仓库克隆失败"
        exit 1
    }
    title_assert "git clone ${target_clone}"
    # 获取 GitHub 仓库的最新提交 ID
    local github_commit=$(git ls-remote "${target_clone}" HEAD | awk '{print $1}')

    # 进入仓库目录
    cd "${tool_name}" || {
        echo "进入仓库目录失败"
        exit 1
    }
    title_assert "cd ${tool_name}"

    # 创建本地分支
    log_title "创建所有本地分支"
    for b in $(git branch -r | grep -v -- '->'); do
        git branch --track ${b##origin/} $b
    done

    # 添加 GitLab 远程仓库
    log_title "添加 GitLab 远程仓库"
    git remote add gitlabtest "${opensource_clone}" || {
        echo "添加 GitLab 远程仓库失败"
        exit 1
    }
    title_assert "git remote add gitlabtest ${opensource_clone}"
    git remote -v
    title_assert "git remote -v"
    git config pull.rebase false
    # 以github为主项目拉取最新代码，合并
    git fetch origin
    #title_assert "git fetch origin"
    git merge origin/master
    #title_assert "git merge origin/master"
    if [ $? -ne 0 ]; then
        echo "合并时遇到冲突，请手动解决冲突后再继续。"
        exit 1
    fi

    # 推送所有分支到 GitLab，没用加--force，原则上不能修改gitlab源代码
    log_title "上传所有分支到 GitLab"
    expect <<-EOF
    set timeout 300
    spawn git push gitlabtest --all
    expect {
        "Username for 'http://10.0.0.66':" { send "${USERNAME}\n"; exp_continue }
        "Password for 'http://${USERNAME}@10.0.0.66':" { send "${PASSWORD}\n" }
    }
    expect eof
EOF
    echo -e "\n"
    local get_target_tag=$(git tag)
    if [ -n "${get_target_tag}" ]; then
        # 推送所有 tags 到 GitLab
        log_title "上传所有 tags 到 GitLab"
        expect <<-EOF
        set timeout 300
    spawn git push --tags gitlabtest
    expect {
        "Username for 'http://10.0.0.66':" { send "${USERNAME}\n"; exp_continue }
        "Password for 'http://${USERNAME}@10.0.0.66':" { send "${PASSWORD}\n" }
    }
    expect eof
EOF
        echo -e "\n"
    fi
    # 调用 log_gitlab 验证 GitHub 和 GitLab 的提交是否一致
    log_gitlab "${opensource_clone}"
}

function clone_push_all() {
       local target_repos=("http://10.0.0.66/opensource/ltp.git"\
                    "http://10.0.0.66/opensource/stress-ng.git"\
                    "http://10.0.0.66/opensource/lmbench-master.git"\
                    "http://10.0.0.66/opensource/sysbench.git"\
                    "http://10.0.0.66/opensource/stream.git"\
                    "http://10.0.0.66/opensource/fio.git"\
                    "http://10.0.0.66/opensource/netperf.git"\
                    "http://10.0.0.66/opensource/iperf.git"\
                    "http://10.0.0.66/opensource/byte-unixbench.git"\
                    "http://10.0.0.66/opensource/x11perf.git"\
                    "http://10.0.0.66/opensource/qperf.git"\
                    "http://10.0.0.66/opensource/bonnie.git"\
                    "http://10.0.0.66/opensource/coremark.git"\
                    "http://10.0.0.66/opensource/memtester.git"\
                    "http://10.0.0.66/opensource/stressapptest.git"\
                    "http://10.0.0.66/opensource/mbw.git"\
                    "http://10.0.0.66/opensource/nbench.git"
                    ) ## gitLab 工具地址 改成gitlab上存在的仓库
    
    local source_repos=("https://github.com/linux-test-project/ltp.git" \
                    "https://github.com/ColinIanKing/stress-ng.git"\
                    "https://github.com/intel/lmbench.git"\
                    "https://github.com/akopytov/sysbench.git"\
                    "https://github.com/jeffhammond/STREAM.git"\
                    "https://github.com/axboe/fio.git"\
                    "https://github.com/HewlettPackard/netperf.git"\
                    "https://github.com/esnet/iperf.git"\
                    "https://github.com/kdlucas/byte-unixbench.git"\
                    "https://github.com/clearlinux-pkgs/x11perf.git"\
                    "https://github.com/linux-rdma/qperf.git"\
                    "https://github.com/y-ken/bonnie.git"\
                    "https://github.com/eembc/coremark.git"\
                    "https://github.com/jnavila/memtester/tree/master.git"\
                    "https://github.com/stressapptest/stressapptest/tree/master.git"\
                    "https://github.com/raas/mbw.git"\
                    "https://github.com/toshsan/nbench.git"
                    )  ## github 开源工具地址 改成github要拉取的仓库

    for ((i = 0; i < ${#target_repos[@]}; i++)); do
        local target_clone=${source_repos[i]}
        local opensource_clone=${target_repos[i]}
        clone_push_single "${target_clone}" "${opensource_clone}"
    done
}

function help() {
    cat >&2 <<-EOF
	 ---------------------------------------------------------------------------------------------------------------------------------------
	| EX : ./gitPullPush.sh -u "username" -p "password" -h "http://A.git http://B.git" -l "http://10.0.0.66/A.git http://10.0.0.66/B.git"   |
    |      ./gitPullPush.sh  -u "username" -p "password"  -a                                                                                |   
	| OPTION  :                                                                                                                             |
	|    -h   : githup address                                                                                                              |
	|    -l   : gitlab address                                                                                                              |
    |    -a   : All pushed from github to gitlab                                                                                            |
    |    -u   : gitlab username                                                                                                             |
    |    -p   : gitlab password                                                                                                             |
	 ---------------------------------------------------------------------------------------------------------------------------------------
EOF
}

# 处理命令行参数
main() {
    local USERNAME=""
    local PASSWORD=""
    local github_repos_str=""
    local gitlab_repos_str=""

    while getopts ":h:l:u:p:a" opt; do
        case $opt in
        "h")
            github_repos_str="${OPTARG}"
            ;;
        "l")
            gitlab_repos_str="${OPTARG}"
            ;;
        "a")
            if [ -z "${OPTARG}" ]; then
                clone_push_all
                exit 0
            else
            #读取文件，将每一行的仓库地址存入数组
                if [ ! -e "${OPTARG}" ];then
                    log_error "文件${OPTARG}不存在，请检查！"
                    exit 1
                    fi
                    while IFS=' ' read -r github_url gitlab_url;do
                        github_repos_str+="${github_url}"
                        github_repos_str+="${gitlab_url}"
                    done < "${OPTARG}"
            fi
            ;;
        "u")
            USERNAME="${OPTARG}"
            ;;
        "p")
            PASSWORD="${OPTARG}"
            ;;
        "?")
            log_error "无效的选项: -${OPTARG}"
            help
            exit 1
            ;;
        esac
    done

    if [ -n "${github_repos_str}" ] && [ -n "${gitlab_repos_str}" ]; then
        local github_repos=($(echo "${github_repos_str}" | tr " " "\n"))
        local gitlab_repos=($(echo "${gitlab_repos_str}" | tr " " "\n"))

        if [ ${#github_repos[@]} -ne ${#gitlab_repos[@]} ]; then
            log_error "提供的GitHub仓库和GitLab仓库数量不一致，请检查参数"
            exit 1
        fi

        for ((i = 0; i < ${#github_repos[@]}; i++)); do
            local target_clone=${github_repos[i]}
            local opensource_clone=${gitlab_repos[i]}
            clone_push_single "${target_clone}" "${opensource_clone}"
        done
    else
        # if [ -z "${github_repos_str}" ] && [ -z "${gitlab_repos_str}" ]; then
        log_error '请提供正确的参数，例如：./gitPullPush.sh -h \"githuba githubb\" -l \"gitlaba gitlabb\" 或者./gitPullPush.sh -a'
        help
        exit 1
        # fi
    fi
}

git_lib
main "$@"
